import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-09-21
 * Time: 19:29
 */

public class Demo1DriverManager {

    public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {

            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2.获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");

            //3.创建Statement对象
            statement = connection.createStatement();

            //4.定义SQL语句
            System.out.println("请输入学生姓名");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.next();
            String sql = "select student_id, sn, name, mail, class_id from student where name = '" + name + "' "; //注意空格

            //4.执行SQL查询语句
            resultSet = statement.executeQuery(sql);

            //遍历结果集
            //有记录返回true,没记录返回false
            while (resultSet.next()) {
                long stuId = resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={1}, 学号={2}, 学生姓名={3}, 邮箱={3}, 班级编号={5}", stuId, stuSn,
                        stuName, stuMail, classId));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (resultSet != null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
